﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GMUtilitiesDotNet.Gestures;
using System.Windows.Input;
using System.Windows;
using GMUtilitiesDotNet.Helpers;
using System.Windows.Controls;
using ThouShaltNotBrickLevelEditor.Code.GeneralObjects;

namespace ThouShaltNotBrickLevelEditor.Gestures
{
    internal sealed class SelectBrickStateGesture : GestureBase
    {
        #region Constructors
        public SelectBrickStateGesture()
        {
            Handled = false;
            ClearData();
        }
        #endregion

        #region Overriden Methods
        public override bool OnMouseLeftButtonDown(MouseButtonEventArgs pArgs)
        {
            BrickStateSelectorView brickStateSelectorView = UIHelpers.FindVisualCurrentOrParent<BrickStateSelectorView>(pArgs.Source as DependencyObject);
            if (brickStateSelectorView == null)
            {
                ClearData();
                return false;
            }

            Image brickStateSelectorImage = brickStateSelectorView.BrickStateSelectorImage;
            BrickSelectorRects brickSelectorRects = brickStateSelectorView.BrickSelectorRects;
            if (brickStateSelectorImage == null || brickSelectorRects == null)
            {
                ClearData();
                return false;
            }

            Point position = pArgs.GetPosition(brickStateSelectorImage);
            BrickStateSelection brickStateSelection = GetBrickStateSelection(position, brickSelectorRects);
            CommandParam = brickStateSelection;
            return brickStateSelection != null;
        }
        #endregion

        #region Methods
        private static BrickStateSelection GetBrickStateSelection(
            Point pMousePosition,
            BrickSelectorRects pBrickSelectorRects)
        {
            List<BrickSelectorRect> brickSelectorRectList = pBrickSelectorRects.GetBrickSelectorRects();
            foreach (BrickSelectorRect brickSelectorRect in brickSelectorRectList)
            {
                Rect brickStateRect = brickSelectorRect.BrickStateRect;
                if (brickStateRect.Contains(pMousePosition))
                {
                    return new BrickStateSelection(
                        brickSelectorRect.BrickTypeName,
                        brickSelectorRect.BrickStateName,
                        brickSelectorRect.BrickStateIndex);
                }
            }

            return null;
        }

        private void ClearData()
        {
            CommandParam = null;
        }
        #endregion
    }
}